﻿using Grow.Domain.EventBus.Cap.PublisherDomainEvents;
using Grow.Module.Service;
using Grow.Scheduler.Job;

namespace Grow.Domain.EventBus.Cap.Jobs
{
    public class RetryPublisherDomainEventJob : JobBase
    {
        private readonly IPublisherDomainEventHandler _publisherHandler;
        private readonly IPublisherDomainEventService _publisherDomainEventService;
        public RetryPublisherDomainEventJob(IServiceContext serviceContext) : base(serviceContext)
        {
            _publisherHandler = _serviceContext.GetRequiredService<IPublisherDomainEventHandler>();

            _publisherDomainEventService = serviceContext.GetRequiredService<IPublisherDomainEventService>();
        }

        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            List<PublisherDomainEventDto> publisherDomainEventDtos = await _publisherDomainEventService.GetPublisherDomainEventsOfNeedRetryAsync(cancellationToken);
            if (publisherDomainEventDtos.Count == 0)
            {
                return;
            }
            _ = Parallel.ForEach(publisherDomainEventDtos, publisherDomainEventDto =>
            {
                _ = Task.Factory.StartNew(async () =>
                {
                    await _publisherHandler.PublisherAsync(publisherDomainEventDto, cancellationToken);
                }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            });
        }
       
    }
}
